package com.example.itcacp.controller;

import com.example.itcacp.dto.response.Result;
import com.example.itcacp.entity.Authority;
import com.example.itcacp.entity.Role;
import com.example.itcacp.entity.User;
import com.example.itcacp.exception.CustomerException;
import com.example.itcacp.repository.mybatis.UserMapper;
import com.example.itcacp.service.AdminService;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import lombok.Data;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/admin")
public class AdminController {

    @Resource //根据对象名称自动注入依赖对象
    private AdminService adminService;
    @Resource
    private UserMapper userMapper;
    /**
     * 登录验证
     */
    @PostMapping("/login")
    public Result login(@RequestBody User user) {  //接收user
        User dbadmin = userMapper.selectUserWithRoleByUsername ( user.getUsername () );
        if (dbadmin == null) {
            throw new CustomerException ("账号不存在");  //抛出一个自定义异常
        }else if ("ADMIN".equals ( dbadmin.getRole ().getRoleName () )) {  // 对比角色
            dbadmin = adminService.login ( user ); //拿到数据库的用户数据
        } else {
            throw new CustomerException ("您的账号权限不足");
        }
        return Result.success ( dbadmin );  //返回给前端
    }

    /**
     * 查询所有用户
     */

    @GetMapping("/selectAll") //接口的路径，全局唯一
    public Result selectAll () {
        List<User> userList = adminService.selectAll();
        return Result.success (userList); //接口返回
    }

    /**
     * 分页查询接口: 所有用户
     *   分页对象包含的数据
     *   total : 数据库表所有数据总的个数
     *   list ： 返回的数据数组
     *   pageNum : 当前的页码
     *   pageSizer ： 每页展示的个数
     * */
    @PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/selectPage")
    public Result selectPage (@RequestParam(defaultValue = "1") Integer pageNum,
                              @RequestParam(defaultValue = "10") Integer pageSize,
                              @RequestParam(required = false) String name,
                              @RequestParam(required = false)String rolename) {  //RequestParam : 参数注解 、 required = false 不强制接收
        PageInfo<User> userPageInfo = adminService.selectPage(pageNum, pageSize, name, rolename);
        return Result.success(userPageInfo);  // 返回分页的对象
    }


    /**
     * 修改用户信息+角色
     * */
    @PutMapping("/update")
    public Result update (@RequestBody User user,
                          @RequestParam String role_name) {
        adminService.update (user, role_name);
        return Result.success ();
    }

    /**
     * 新增用户添加接口  RequestBody注解用于接收前端传回来的json数据
     */

    @PostMapping("/add")
//    @PreAuthorize("hasRole('ADMIN')")
    public Result add (@RequestBody User user,
                       @RequestParam String role_name) {
        adminService.add(user, role_name);
        return Result.success ();
    }

    /**
     * 删除接口 @PathVariable路径参数
     * */
    @DeleteMapping("/delete/{id}")
    public Result delete (@PathVariable Long id) {
        adminService.deleteUserById(id);
        return Result.success ();
    }

    /**
     * 批量删除接口
     * */
    @DeleteMapping("/deleteUserBatch")
    public Result deleteUserBatch (@RequestBody List<User> userList) {
        for (User user : userList) {
            this.delete ( user.getUser_id () );
        }
        return Result.success ();
    }



    /**
     * 查询所有角色
     */

    @GetMapping("/selectRoleAll") //接口的路径，全局唯一
    public Result selectRoleAll () {
        List<Role> roleList = adminService.selectRoleAll ();
        return Result.success (roleList); //接口返回
    }

    /**
     * 分页查询接口: 角色
     * */
    @GetMapping("/selectRolePage")
    public Result selectRolePage (@RequestParam(defaultValue = "1") Integer pageNum,
                              @RequestParam(defaultValue = "5") Integer pageSize,
                              @RequestParam(required = false) String roleName,
                              @RequestParam(required = false)String authorityName) {  //RequestParam : 参数注解 、 required = false 不强制接收
        PageInfo<Role> rolePageInfo = adminService.selectRolePage ( pageNum, pageSize, roleName, authorityName );
        return Result.success(rolePageInfo);  // 返回分页的对象
    }

    /**
     * 添加角色
     * */
    @PostMapping("/roleAdd")
    public Result roleAdd (@RequestBody RoleRequest request) {
        adminService.addRole ( request.getRole (), request.getAuthorityNames () );
        return Result.success ();
    }
    /**
     *  新增一个请求类来封装 Role 和 authorityNames
     */
    @Data
    static class RoleRequest {
        private Role role;
        private List<String> authorityNames;
    }

    /**
     * 删除角色
     */
    @DeleteMapping("/roleDel/{roleId}")
    public Result roleDel (@PathVariable Long roleId) {
        adminService.deleteRoleById ( roleId );
        return Result.success ();
    }

    /**
     * 修改角色+权限
     * */
    @PutMapping("/updateRole")
    public Result updateRole (@RequestBody RoleRequest updateRequest) {
        adminService.updateRole ( updateRequest.getRole (), updateRequest.getAuthorityNames () );
        return Result.success ();
    }


    /**
     * 查询所有权限
     */

    @GetMapping("/selectAuthAll") //接口的路径，全局唯一
    public Result selectAuthAll () {
        List<Authority> authList = adminService.selectAuthAll ();
        return Result.success (authList); //接口返回前端
    }

    /**
     * 分页查询接口: 权限
     * */
    @GetMapping("/selectAuthPage")
    public Result selectAuthPage (@RequestParam(defaultValue = "1") Integer pageNum,
                                  @RequestParam(defaultValue = "5") Integer pageSize,
                                  @RequestParam(required = false)String authorityName) {  //RequestParam : 参数注解 、 required = false 不强制接收
        PageInfo<Authority> AuthPageInfo = adminService.selectAuthPage ( pageNum, pageSize, authorityName );
        return Result.success(AuthPageInfo);  // 返回分页的对象
    }

    /**
     * 添加权限
     * */
    @PostMapping("/addAuth")
    public Result addAuth (@RequestBody Authority authority) {
        adminService.addAuth ( authority );
        return Result.success ();
    }

    /**
     * 删除权限
     */
    @DeleteMapping("/authDel/{authorityId}")
    public Result authDel (@PathVariable Long authorityId) {
        adminService.deleteAuthById ( authorityId );
        return Result.success ();
    }

    /**
     * 修改权限
     * */
    @PutMapping("/updateAuth")
    public Result updateAuth (@RequestBody Authority authority) {
        adminService.updateAuth ( authority );
        return Result.success ();
    }

}
